package com.gqzdev.xblog.controller.admin;

import com.alibaba.fastjson.JSON;
import com.gqzdev.xblog.controller.home.IndexController;
import com.gqzdev.xblog.util.FileUploadUtil;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName UeditorController
 * @Description
 * @Author ganquanzhong
 * @Date2020/6/7 18:23
 * @Version
 **/

@Controller
@RequestMapping("/admin/ueditor")
public class UeditorController {

    @Value("${xblog.file.path}")
    private String filePath;

    @Value("${xblog.server.path}")
    private String serverPath;

    @Value("${xblog.file.imageUrlPrefix}")
    private String imageUrlPrefix;

    @Autowired
    private FileUploadUtil fileUploadUtil;

    /**
     * 初始化UEditor上传文件、图片等配置
     *  https://blog.csdn.net/u013792404/article/details/88297239
     *  https://blog.csdn.net/weixin_41420919/article/details/104351096
     * 一共有两次请求
     *      第一次目的是加载config.json；将其中的数据以json形式返回；
     *      第二次就是上传图片【或者其他类型】，成功后返回json格式数据：
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/editorController")
    public void initController(MultipartFile upfile, @RequestParam(value = "source[]",required = false) String[] sources, HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding("UTF-8");
            //设置response查询的码表
            response.setCharacterEncoding("UTF-8");
            //通过一个头"Content-type"告知客户端使用何种码表
            response.setHeader("Content-Type", "text/html;charset=UTF-8");
            String action = request.getParameter("action");

//            System.out.println("请求url : " + request.getRequestURL().toString());
            System.out.println("上传类型action:" + action);

            // 文件上传的路径
            String rootPath = filePath;
            String result = null;

            //第一步，读取配置文件
            if ("config".equals(action)) {
                // 读取config.json配置文件，将配置文件数据以json格式返回
                String configPath = "/config.json";
                InputStream inStream = IndexController.class.getResourceAsStream(configPath);
                StringBuilder builder = new StringBuilder();
                try {
                    InputStreamReader reader = new InputStreamReader(inStream, "UTF-8");
                    BufferedReader bfReader = new BufferedReader(reader);
                    String tmpContent = null;
                    while ((tmpContent = bfReader.readLine()) != null) {
                        builder.append(tmpContent);
                    }
                    bfReader.close();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                // 过滤输入字符串, 剔除多行注释以及替换掉反斜杠
                result = builder.toString().replaceAll("/\\*[\\s\\S]*?\\*/", "").replaceAll(" ", "");
//                System.out.println("result:" + result);
            } else if ("uploadimage".equals(action)) {
                // 上传文件
                String originalFilename = upfile.getOriginalFilename();
                String type = originalFilename.substring(originalFilename.indexOf("."), originalFilename.length());
                long size = upfile.getSize();
                String filename = System.currentTimeMillis() +"."+type;
//                System.out.println(originalFilename);
//                System.out.println(size);
                //中间路径-时间年月日
                String middlePath = DateFormatUtils.format(new Date(), "yyyyMMdd") + "/";
                String fileFullName = rootPath + middlePath + filename;
                // 图片访问地址（tomcat服务器）
                String url = imageUrlPrefix +middlePath+ filename;
                try {
                    File file = new File(fileFullName);
                    if(!file.getParentFile().exists()) {
                        file.getParentFile().mkdirs() ;
                    }
                    // 文件上传
                    upfile.transferTo(file);
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("state", "SUCCESS");
                    map.put("original", originalFilename);
                    map.put("size", size);
                    map.put("title", originalFilename);
                    map.put("type", type);
                    map.put("url", url);
                    result = JSON.toJSONString(map);
//                    System.out.println("result : " + result);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else if("uploadvideo".equals(action)){
                //上传视频
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("state", "error");
//                map.put("original", originalFilename);
//                map.put("size", size);
//                map.put("title", originalFilename);
//                map.put("type", type);
//                map.put("url", url);
                result = JSON.toJSONString(map);
            }else if ("catchimage".equals(action)){
                // 远程图片上传
                System.out.println("远程图片上传");
                Map<String,Object> map = new HashMap<>();
                map.put("list",fileUploadUtil.ueditorUpload(sources));
                map.put("state","SUCCESS");
                result = JSON.toJSONString(map);
//                System.out.println("result : " + result);
            }
            // 可扩展其他的上传
            else{
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("state", "error");
//                map.put("original", originalFilename);
//                map.put("size", size);
//                map.put("title", originalFilename);
//                map.put("type", type);
//                map.put("url", url);
                result = JSON.toJSONString(map);
            }

            // response响应
            PrintWriter writer = response.getWriter();
            writer.write(result);
            writer.flush();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
